#include "MultiTask.h"

#ifdef __cplusplus            // 判断当前编译环境是C还是C++
#define nullptr 0                 // C++环境下，编译器预先定义一个宏_cplusplus      
#else
#define nullptr (void *)0         // C语言环境
#endif


/* Task handle list head. */
static MultiTask* tasklist = nullptr; 

int MultiTaskStart(MultiTask* task, MultiTaskCnt_t timing, MultiTaskCallback_t callback, void* userData)
{
    if (!task || !callback ) {
        return -1;
    }
    MultiTask** nextTask = &tasklist;
    /* Remove the existing target task. */
    for (; *nextTask; nextTask = &(*nextTask)->next) {
        if (task == *nextTask) {
            *nextTask = task->next; /* remove from list */
            break;
        }
    }

    /* Init task. */
    task->tik      = timing ;
    task->deadline =  timing;
    task->callback = callback;
    task->userData = userData;
    

    /* Insert task. */
    task->next = *nextTask;
    *nextTask = task;

    return 0;
}

int MultiTaskStop(MultiTask* task)
{
    MultiTask** nextTask = &tasklist;
    /* Find and remove task. */
    for (; *nextTask; nextTask = &(*nextTask)->next) {
        MultiTask* entry = *nextTask;
        if (entry == task) {
            *nextTask = task->next;
            break;
        }
    }
    return 0;
}

int MultiTaskYield(void)
{
    MultiTask* entry = tasklist;
    for (; entry; entry = entry->next) {
        entry->tik-- ;
        if(entry->tik == 0) {
            entry->tik = entry->deadline ; 
            /* call callback */
            if (entry->callback) {
                entry->callback(entry, entry->userData) ;
            }
        }
    }

    return 0;
}
